//TODO: Some(_) => seed.deserialize(MapKey {de: &mut *self.de }).map(Some),
//TODO: self.ignore_value()?;

use crate::error::{Result, ErrorCode, Error};
use crate::reader::{self, Reference};

use std::fmt::{self, Debug};
use serde::de::{self, Expected, Unexpected};

pub struct Deserializer<R> {
    read: R,
    scratch: Vec<u8>,
}

impl<'de, R> Deserializer<R> 
where 
    R: reader::Read<'de>
{
    pub fn new(read: R) -> Self {
        Self {
            read,
            scratch: Vec::new(),
        }
    }
}


impl<'a> Deserializer<reader::SliceRead<'a>> {
    pub fn from_slice(slice: &'a [u8]) -> Self {
        Deserializer::new(reader::SliceRead::new(slice))
    }
}


impl<'de, R: reader::Read<'de>> Deserializer<R> {
    // must be end of the line, 
    // because no end of char in gtp message standard.
    #[inline]
    pub fn end(&mut self) -> Result<()> {
        match self.peek()?{
            Some(_) => Err(self.error(ErrorCode::TrailingCharacter)),
            None => Ok(()),
        }
    }
    // Ok(None) => Eof;  Ok(byte) => byte
    #[inline]
    fn peek(&self) -> Result<Option<u8>> {
        self.read.peek()
    }
    #[inline]
    fn eat(&mut self) {
        self.read.discard();
    }

    #[inline]
    fn next(&mut self) -> Result<Option<u8>> {
        self.read.next()
    }

    #[inline]
    fn position(&self) -> usize {
        self.read.byte_offset()
    }

    #[inline]
    fn is_key_char(&self, byte: u8) -> bool {
        self.read.is_key_byte(byte)
    }

    #[inline]
    fn peek_or_null(&self) -> Result<u8>{
        Ok(self.peek()?.unwrap_or(0_u8)) 
    }

    #[inline]
    fn error(&self, reason: ErrorCode) -> Error {
        Error::syntax(reason, self.position())
    }
    #[cold]
    fn peek_invalid_type(&mut self, exp: &dyn Expected) -> Error {
        match self.peek_or_null().unwrap_or(b'\x00'){
            b'-' => {
                self.eat();
                match self.parse_integer(false) {
                    Ok(n) => n.invalid_type(exp),
                    Err(err) => err,
                }
            },
            b'0'..=b'9' => match self.parse_integer(true){
                Ok(n) => n.invalid_type(exp),
                Err(err) => err,
            },
            b'[' => de::Error::invalid_type(Unexpected::Seq, exp),
            b'{' => de::Error::invalid_type(Unexpected::Map, exp),
            _ => self.error(ErrorCode::ExpectedSomeValue),
        }
    }
}


pub enum ParserNumber {
    I64(i64),
    U64(u64),
    F64(f64),
}

impl PartialEq for ParserNumber {
    fn eq(&self, other: &Self) -> bool {
        match (self,  other) {
            (ParserNumber::I64(s), ParserNumber::I64(o)) => *s == *o,
            (ParserNumber::U64(s), ParserNumber::U64(o)) => *s == *o,
            (ParserNumber::F64(s), ParserNumber::F64(o)) => *s == *o,
            _ => false,
        }
    }
}

impl Debug for ParserNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
        match self {
            ParserNumber::I64(i) => Debug::fmt(i, f),
            ParserNumber::U64(u) => Debug::fmt(u, f),
            ParserNumber::F64(n) => Debug::fmt(n, f),
        }
    }
}

impl ParserNumber {
    fn visit<'de, V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de>, 
    {
        match self {
            ParserNumber::F64(x) => visitor.visit_f64(x),
            ParserNumber::U64(x) => visitor.visit_u64(x),
            ParserNumber::I64(x) => visitor.visit_i64(x),
        }
    }

    fn invalid_type(self, exp: &dyn Expected) -> Error {
        match self {
            ParserNumber::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp),
            ParserNumber::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp),
            ParserNumber::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp),
        }
    }
}





impl<'de, R: reader::Read<'de>> Deserializer<R> {
    // '='
    #[inline]
    pub fn parse_whilespace(&mut self) -> Result<Option<u8>>{
        loop {
            match self.peek()? {
                Some(b' ' | b'\t' | b'\r') => self.eat(),
                other => { return Ok(other) }
            }
        }
    }
    #[inline]
    pub fn parse_comma(&mut self) -> Result<()> {
        self.parse_object_sign(b',', ErrorCode::ExpectedEquals)
    }
    #[inline]
    pub fn parse_object_equals(&mut self) -> Result<()> {
        self.parse_object_sign(b'=', ErrorCode::ExpectedEquals)
    }
    #[inline]
    pub fn parse_object_sign(&mut self, byte: u8, reason: ErrorCode) -> Result<()> {
        match self.peek()? {
            Some(s)=> {
                if s == byte {
                    self.eat();
                    Ok(())
                }
                else{
                    Err(self.error(reason))
                }
            }
            None => Err(self.error(ErrorCode::EofWhileParsingObject)),
        }
    }


    // '}' ','
    #[inline]
    pub fn parse_object_end(&mut self) -> Result<()> {
        match self.peek()? {
            Some(b'}') => {
                self.eat();
                Ok(())
            }
            Some(b',') => Err(self.error(ErrorCode::TrailingComma)),
            Some(_) => Err(self.error(ErrorCode::TrailingCharacter)),
            None => Err(self.error(ErrorCode::EofWhileParsingObject)),
        }
    }
    // ']', ','
    #[inline]
    pub fn parse_array_end(&mut self) -> Result<()> {
        match self.peek()? {
            Some(b']') => {
                self.eat();
                Ok(())
            }
            Some(b',') => Err(self.error(ErrorCode::TrailingComma)),
            Some(_) => Err(self.error(ErrorCode::TrailingCharacter)),
            None => Err(self.error(ErrorCode::EofWhileParsingObject)),
        }
    }


    pub fn parse_integer(&mut self, positive: bool) -> Result<ParserNumber> {
        let next = match self.next()? {
            Some(b) => b,
            None => return Err(self.error(ErrorCode::EofWhileParsingValue)),
        };
        
        match next {
            b'0' => {
                match self.peek_or_null()? {
                    b'0'..=b'9' => Err(self.error(ErrorCode::InvalidNumber)),
                    _ => self.parse_number(positive, 0),
                }
            }
            c @ b'1'..=b'9' => {
                let mut significand = (c - b'0') as u64;

                loop {
                    match self.peek_or_null()? {
                        c @ b'0'..=b'9' => {
                            let digit = (c - b'0') as u64;
                            significand = significand * 10 + digit;
                            self.eat();
                        }
                        _ => {// not the [0-9]
                            return self.parse_number(positive, significand);
                        }
                    }
                }
            }
            _ => Err(self.error(ErrorCode::InvalidNumber)),

        }
    }
    fn parse_number(&mut self, positive: bool, significand: u64) -> Result<ParserNumber> {
        Ok (
            match self.peek_or_null() ? {
                b'.' => { 
                    self.eat();
                    ParserNumber::F64(self.parse_decimal(positive, significand)?)
                }
                _ => {
                    if positive {
                        ParserNumber::U64(significand)
                    } else {
                        let neg = (significand as i64).wrapping_neg();
                        if neg >= 0{
                            // -0 is float
                            ParserNumber::F64(-(significand as f64))
                        } else {
                            ParserNumber::I64(neg)
                        }
                    }
                }
            }
        )
    }
    fn parse_decimal(&mut self, positive: bool, mut significand: u64) -> Result<f64> {
        let mut exponent_after_decimal_point = 0;

        while let c @ b'0'..=b'9' = self.peek_or_null()? {
            let digit = (c - b'0') as u64;
            self.eat();
            significand = significand * 10 + digit;
            exponent_after_decimal_point += 1;
        }

        // no digit after decimal_point, if the number_str is [11111.] => error
        if exponent_after_decimal_point == 0 {
            match self.peek() ? {
                Some(_) => return Err(self.error(ErrorCode::InvalidNumber)),
                None => return Err(self.error(ErrorCode::EofWhileParsingValue)),
            }
        }
        self.f64_from_parts(positive, significand, exponent_after_decimal_point)
    }
    fn f64_from_parts(&self, positive: bool, significand: u64, exponent: u32) -> Result<f64> {
        let f = (significand as f64) / (10_u32.pow(exponent) as f64);
        if !f.is_infinite(){
            Ok(if positive { f } else { -f } )
        } else {
            Err(self.error(ErrorCode::NumberOutOfRange))
        }
    }

        
    fn scan_integer128(&mut self, buf: &mut String) -> Result<()> {
        match self.peek_or_null()? {
            b'0' => { // only  '0' is valid;  else illegal
                self.eat();
                match self.peek_or_null()? {
                    b'0'..=b'9' => Err(self.error(ErrorCode::InvalidNumber)),
                    _ => Ok(()),
                }
            }
            c @ b'1'..=b'9' => {
                self.eat();
                buf.push(c as char);
                while let c @ b'0'..=b'9' = self.peek_or_null()? {
                    self.eat();
                    buf.push(c as char)
                }
                Ok(())
            }
            _ => Err(self.error(ErrorCode::InvalidNumber)),
        }
    }

}


// call peek() :
//      None => return Error; 
//      Some => return b;
macro_rules! peek_char_or_err {
    ($method:ident) => {
        match $method.peek()? {
            Some(b) => b,
            None => {
                return Err($method.error(ErrorCode::EofWhileParsingValue))
            }
        }
    };
}
macro_rules! deserialize_number {
    ($method: ident) => {
        deserialize_number!($method, deserialize_number);
    };
    ($method: ident, $using: ident) => {
        fn $method<V>(self, visitor: V) -> Result<V::Value> 
        where 
            V: de::Visitor<'de>, 
        { 
            self.$using(visitor)
        }
    };
}

impl<'de, R: reader::Read<'de>> Deserializer<R> {
    #[inline]
    fn deserialize_number<'any, V>(&mut self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'any>,
    {
        let peek = peek_char_or_err!(self);
        match peek {
            b'-' => {
                self.eat();
                self.parse_integer(false)?.visit(visitor)
            }
            b'0'..=b'9' => {
                self.parse_integer(true)?.visit(visitor)
            }
            _ => {
                Err(self.error(ErrorCode::ExpectedSomeValue))
            }
        }
    }
}

impl <'de, 'a, R: reader::Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
    type Error = Error;

    #[inline]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de>,
    {
        let peek = peek_char_or_err!(self);
        match peek {
            b'[' => {
                self.eat();
                let ret = visitor.visit_seq(SeqAccess::new(self));
                match (ret, self.parse_array_end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            b'{' => {
                self.eat();
                let ret = visitor.visit_map(MapAccess::new(self));
                match (ret, self.parse_object_end()){
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            c if self.is_key_char(c)  =>  {
                self.scratch.clear();
                match self.read.parse_to_slice(&mut self.scratch)? {
                    Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b),
                    Reference::Copied(c) => visitor.visit_bytes(c),
                }
            }
            _ => {
                Err(self.error(ErrorCode::ExpectedSomeValue))
            }
        }
    }


    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de>,
    { 
        let peek = peek_char_or_err!(self);
        match peek {
            b'1' => {
                self.eat();
                visitor.visit_bool(true)
            }
            b'0' => {
                self.eat();
                visitor.visit_bool(false)
            }
            _ => {
                Err(self.peek_invalid_type(&visitor))
            }
        }
    }
    
    deserialize_number!(deserialize_i8);
    deserialize_number!(deserialize_i16);
    deserialize_number!(deserialize_i32);
    deserialize_number!(deserialize_i64);

    deserialize_number!(deserialize_u8);
    deserialize_number!(deserialize_u16);
    deserialize_number!(deserialize_u32);
    deserialize_number!(deserialize_u64);

    deserialize_number!(deserialize_f64);
    deserialize_number!(deserialize_f32);

    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> , 
    {
        let mut buf = String::new();

        if peek_char_or_err!(self) == b'-' {
            self.eat();
            buf.push('-');
        }

        self.scan_integer128(&mut buf)?;

        match buf.parse::<i128>() {
            Ok(int) => visitor.visit_i128(int),
            Err(_) => Err(self.error(ErrorCode::NumberOutOfRange)),
        }
    }

    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    {
        if peek_char_or_err!(self)  == b'-' {
            return Err(self.error(ErrorCode::NumberOutOfRange));
        }

        let mut buf = String::new();
        self.scan_integer128(&mut buf)?;

        match buf.parse::<u128>(){
            Ok(uint) => visitor.visit_u128(uint),
            Err(_) => Err(self.error(ErrorCode::NumberOutOfRange)),
        }
    }

    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de>,
    { 
        self.deserialize_str(visitor)
    }

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    {
        self.scratch.clear();
        match self.read.parse_to_str(&mut self.scratch)? {
            Reference::Borrowed(b) => visitor.visit_borrowed_str(b),
            Reference::Copied(c) => visitor.visit_str(c),
        }
    }
    
    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        self.deserialize_str(visitor)
    }


    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> , 
    { 
        self.scratch.clear();
        match self.read.parse_to_slice(&mut self.scratch)? {
            Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b),
            Reference::Copied(c) => visitor.visit_bytes(c),
        }
    }
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        self.deserialize_bytes(visitor)
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        match self.peek()? {
            Some(_) => (),
            None => return visitor.visit_none(),
        }

        visitor.visit_some(self)
    }
    fn deserialize_unit<V>(self, _: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        Err(self.error(ErrorCode::EofWhileParsingValue))
    }


    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        let _ = name;
        visitor.visit_newtype_struct(self)
    }
    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        match peek_char_or_err!(self) {
            b'[' => {
                self.eat();
                let ret = visitor.visit_seq(SeqAccess::new(self));

                match (ret, self.parse_array_end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => Err(self.peek_invalid_type(&visitor)),
        }
    }
    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V>(self, _name: &'static str, _len: usize, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    {
        self.deserialize_seq(visitor)
    }
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        match peek_char_or_err!(self) {
            b'{' => {
                self.eat();
                let ret = visitor.visit_map(MapAccess::new(self));
                
                 match (ret, self.parse_object_end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => Err(self.peek_invalid_type(&visitor)),
        }
    }
    fn deserialize_struct<V>(self, _name: &'static str, _: &'static [&'static str], visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        match peek_char_or_err!(self) {
            b'[' => {
                self.eat();
                let ret = visitor.visit_seq(SeqAccess::new(self));
                match (ret, self.parse_array_end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            b'{' => {
                self.eat();
                let ret = visitor.visit_map(MapAccess::new(self));
                match (ret, self.parse_object_end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            c if self.is_key_char(c)  =>  {
                let ret = visitor.visit_map(MapAccess::new_for_struct(self));
                match (ret, self.end()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => Err(self.peek_invalid_type(&visitor)),
        }
    }
    fn deserialize_enum<V>(self, _: &'static str, _: &'static [&'static str], visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        match peek_char_or_err!(self) {
            b'{' => {
                self.eat();
                let value = visitor.visit_enum(VariantAccess::new(self))?;
                
                match self.peek()? {
                    Some(b'}') => {
                        self.eat();
                        Ok(value)
                    }
                    Some(_) => Err(self.error(ErrorCode::ExpectedSomeValue)),
                    None => Err(self.error(ErrorCode::EofWhileParsingObject)),
                }
            }
            c if self.is_key_char(c) => visitor.visit_enum(UnitVariantAccess::new(self)),
            _ => Err(self.peek_invalid_type(&visitor)),
        }
    }

    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> 
    { 
        self.deserialize_str(visitor)
    }

    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    { 
        //TODO: self.ignore_value()?;
        visitor.visit_unit()
    }

}


struct SeqAccess<'a, R> {
    de: &'a mut Deserializer<R>,
    first : bool,
}

impl<'a, R: 'a> SeqAccess<'a, R> {
    fn new(de: &'a mut Deserializer<R> ) -> Self {
        SeqAccess { de, first: true }
    }
}

impl<'de, 'a, R: reader::Read<'de>> de::SeqAccess<'de> for SeqAccess<'a, R> {
    type Error = Error;
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> 
    where 
        T: de::DeserializeSeed<'de>,
    {
        let peek = match self.de.peek()? {
            Some(b']') => {
                return Ok(None);
            }
            Some(b',') if !self.first => {
                self.de.eat();
                self.de.peek()?
            }
            Some(b) => {
                if self.first {
                    self.first = false;
                    Some(b)
                } else {
                    return Err(self.de.error(ErrorCode::ExpectedListCommaOrEnd))
                }
            }
            None => {
                return Err(self.de.error(ErrorCode::EofWhileParsingList));
            }
        };
        match peek {
            Some(b']') => Err(self.de.error(ErrorCode::TrailingComma)),
            Some(_) => Ok(Some(seed.deserialize(&mut *self.de)?)),
            None => Err(self.de.error(ErrorCode::EofWhileParsingValue)),
        }
    }
}

struct MapAccess<'a, R> {
    de: &'a mut Deserializer<R>,
    first: bool,
    has_end_sign: bool,
}

impl<'a, R> MapAccess<'a, R> {
    fn new(de: &'a mut Deserializer<R>) -> Self {
        Self { de, first: true, has_end_sign: true}
    }
    fn new_for_struct(de: &'a mut Deserializer<R>) -> Self {
        Self { de, first: true, has_end_sign:false }
    }
}


impl<'de, 'a, R: reader::Read<'de>> de::MapAccess<'de> for MapAccess<'a, R> {
    type Error = Error;

    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> 
    where 
        K: de::DeserializeSeed<'de> 
    {
       let peek = match self.de.peek()? {
            // map with '' 
            Some(b'}') if self.has_end_sign => {
                return Ok(None)
            }
            Some(b',') if !self.first => { //xxx,Cxxx => Some(C)
                self.de.eat();
                self.de.peek()?
            }
            Some(b) => { // ^C => Some(C)
                if self.first {
                    self.first = false;
                    Some(b)
                } else {
                    return Err(self.de.error(ErrorCode::ExpectedObjectCommaOrEnd));
                }
            }
            None => {
                // struct with eof
                if !self.has_end_sign {
                    return Ok(None);
                } else {
                    return Err(self.de.error(ErrorCode::EofWhileParsingObject));
                }
            }
        };
        match peek {
            Some(b'}') => Err(self.de.error(ErrorCode::TrailingComma)),
            //TODO: deserialize for all kinds of Type as Key in Map
            //TODO: Some(_) => seed.deserialize(MapKey {de: &mut *self.de }).map(Some),
            Some(_) => seed.deserialize(&mut *self.de).map(Some),
            None => Err(self.de.error(ErrorCode::EofWhileParsingValue)),
        }
    }

    fn next_value_seed<V>(&mut self, seed: V)  -> Result<V::Value>
    where 
        V: de::DeserializeSeed<'de> ,
    {
        self.de.parse_object_equals()?;
        seed.deserialize(&mut *self.de)
    }

}


struct VariantAccess<'a, R> {
    de: &'a mut Deserializer<R>
}
impl<'a, R> VariantAccess<'a, R> {
    fn new(de: &'a mut Deserializer<R>) -> Self {
        Self { de }
    }
}

impl<'de, 'a, R: reader::Read<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R>
{
    type Error = Error;
    type Variant = Self;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> 
    where 
        V: de::DeserializeSeed<'de> , 
    {
        let val = seed.deserialize(&mut *self.de)?;
        self.de.parse_object_equals()?;
        Ok((val, self))
    }
}


impl<'de, 'a, R: reader::Read<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> 
{
    type Error = Error;
    //enum E {A, B}
    fn unit_variant(self) -> Result<()> {
        de::Deserialize::deserialize(self.de)
    }
    //enum E {A(u8)},
    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> 
    where 
        T: de::DeserializeSeed<'de> 
    {
        seed.deserialize(self.de)
    }
    //enum A{B(s1,s2)}
    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de>,
    {
        de::Deserializer::deserialize_seq(self.de, visitor)
    }
    //enum A{B{r:u8, b: u8}}
    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> 
    where 
        V: de::Visitor<'de> ,
    {
        de::Deserializer::deserialize_struct(self.de, "", fields, visitor)
    }
}



struct UnitVariantAccess<'a, R: 'a> {
    de: &'a mut Deserializer<R>,
}

impl<'a, R: 'a> UnitVariantAccess<'a, R> {
    fn new(de: &'a mut Deserializer<R>) -> Self {
        UnitVariantAccess { de }
    }
}

impl<'de, 'a, R: reader::Read<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> {
    type Error = Error;
    type Variant = Self;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
    where
        V: de::DeserializeSeed<'de>,
    {
        let variant = seed.deserialize(&mut *self.de)?;
        Ok((variant, self))
    }
}

impl<'de, 'a, R: reader::Read<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> {
    type Error = Error;

    fn unit_variant(self) -> Result<()> {
        Ok(())
    }

    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
    where
        T: de::DeserializeSeed<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"newtype variant",
        ))
    }

    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"tuple variant",
        ))
    }

    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"struct variant",
        ))
    }
}





pub fn from_trait<'de, R, T>(read: R) -> Result<T> 
where 
    R: reader::Read<'de>,
    T: de::Deserialize<'de>,
{
    let mut de = Deserializer::new(read);
    let value = de::Deserialize::deserialize(&mut de)?;
    de.end()?;
    Ok(value)
}


#[cfg(test)]
mod test{
    use super::*;
    use crate::from_str;
    use crate::from_slice;
    #[test]
    fn use_deserializer(){
        let mut de = Deserializer::from_slice(b"X01=1");
        assert_eq!(Some(b'X'), de.peek().unwrap());
        de.eat();
        assert_eq!(Some(b'0'), de.peek().unwrap());

        assert_eq!(Some(b'0'), de.next().unwrap())
    }

    #[test]
    fn parse_flags(){ // parse "  "   '='  '}'  ']' ','
        let mut de = Deserializer::from_slice(b"   =,}]");
        assert_eq!(Some(b'='), de.parse_whilespace().unwrap());
        assert!(de.parse_object_equals().is_ok()); 
        assert!(de.parse_comma().is_ok()); 
        assert!(de.parse_object_end().is_ok());
        assert!(de.parse_array_end().is_ok());
    }
    #[test]
    fn parse_number_with_leading_0() {
        // "-0" => F64(-0.0)
        let mut de = Deserializer::from_slice(b"0");
        assert!(de.parse_integer(false)
            .is_ok_and(|f| f == ParserNumber::F64(-0.0))
        );

        // "0" => U64(0)
        let mut de = Deserializer::from_slice(b"0");
        assert!(de.parse_integer(true)
            .is_ok_and(|u| u == ParserNumber::U64(0))
        );

        //ErrorCode::EofWhileParsingValue if "0."
        let mut de = Deserializer::from_slice(b"0.");
        assert!(de.parse_integer(false)
            .is_err_and(|e| e.code() == &ErrorCode::EofWhileParsingValue)
        );

        //InvalidNumber
        let mut de = Deserializer::from_slice(b"00");
        assert!(de.parse_integer(false)
            .is_err_and(|e| e.code() == &ErrorCode::InvalidNumber)
        );
        let mut de = Deserializer::from_slice(b"01");
        assert!(de.parse_integer(false)
            .is_err_and(|e| e.code() == &ErrorCode::InvalidNumber)
        );
        {
            let mut de = Deserializer::from_slice(b"000012345");
            assert!(de.parse_integer(true)
                .is_err_and(|e| e.code() == &ErrorCode::InvalidNumber)
            );
        }
    }

    #[test]
    fn parse_i64(){
        let mut de = Deserializer::from_slice(b"12345");
        assert!(de.parse_integer(false)
            .is_ok_and(|pn| pn == ParserNumber::I64(-12345))
        );
    }
    #[test]
    fn parse_u64(){
        let mut de = Deserializer::from_slice(b"12345");
        assert!(de.parse_integer(true)
            .is_ok_and(|pn| pn == ParserNumber::U64(12345))
        );

        let mut de = Deserializer::from_slice(b"123x");
        assert!(de.parse_integer(true)
            .is_ok_and(|pn| pn == ParserNumber::U64(123))
        );
    }
    //Not-support Exponent format float
    #[test]
    fn parse_f64(){
        let mut de = Deserializer::from_slice(b"12345.124");
        assert!(de.parse_integer(true)
            .is_ok_and(|pn| pn == ParserNumber::F64(12345.124))
        );
        let mut de = Deserializer::from_slice(b"123.333e");
        assert!(de.parse_integer(true)
            .is_ok_and(|n| n == ParserNumber::F64(123.333))
        );
        let mut de = Deserializer::from_slice(b"123.333,");
        assert!(de.parse_integer(true)
            .is_ok_and(|n| n == ParserNumber::F64(123.333))
        );
        let mut de = Deserializer::from_slice(b"123.333]");
        assert!(de.parse_integer(true)
            .is_ok_and(|n| n == ParserNumber::F64(123.333))
        );
        let mut de = Deserializer::from_slice(b"123.333}");
        assert!(de.parse_integer(true)
            .is_ok_and(|n| n == ParserNumber::F64(123.333))
        );

        // error-case
        let mut de = Deserializer::from_slice(b"123.");
        assert!(de.parse_integer(true)
            .is_err_and(|e| e.code() == &ErrorCode::EofWhileParsingValue)
        );
    }

    #[test]
    fn test_from_str() {
        { //i32 = 0
            let i: i32 = from_str("0").unwrap();
            assert_eq!(0, i);
        }
        { //i32
            let i: i32 = from_str("-12345").unwrap();
            assert_eq!(-12345, i);
        }
        {// u32
            let i: u32 = from_str("12345").unwrap();
            assert_eq!(12345, i);
        }
        {// f32
            let i: f32 = from_str::<f64>("12345.01").unwrap() as f32;
            assert_eq!(12345.01, i);
        }
        {//f64
            let i: f64 = from_str("12345.01").unwrap();
            assert_eq!(12345.01, i);
        }
        {//f64 expection
            assert!(
                from_str::<f64>("12345.01,")
                    .is_err_and(|e| e.code() == & ErrorCode::TrailingCharacter)
            );
            assert!(
                from_str::<f64>("12345.01]")
                    .is_err_and(|e| e.code() == & ErrorCode::TrailingCharacter)
            );
            assert!(
                from_str::<f64>("12345.01}")
                    .is_err_and(|e| e.code() == & ErrorCode::TrailingCharacter)
            );
        }
        {//i128
            let i: i128 = from_str("1").unwrap();
            assert_eq!(1_i128, i);

            let i: i128 = from_str("123456789012345678901234444").unwrap();
            assert_eq!(123456789012345678901234444_i128, i);

            let i: i128 = from_str("-1").unwrap();
            assert_eq!(-1_i128, i);

            let i: i128 = from_str("-123456789012345678901234444").unwrap();
            assert_eq!(-123456789012345678901234444_i128, i);
        }
        {//u128
            let u: u128 = from_str("1").unwrap();
            assert_eq!(1_u128, u);

            let u: u128 = from_str("123456789012345678901234444").unwrap();
            assert_eq!(123456789012345678901234444_u128, u);
        }
        {//String
            let s = from_str::<String>("123456").unwrap();
            assert_eq!("123456", s);
        }
        {//&str 
            let s = from_str::<&str>("123456").unwrap();
            assert_eq!("123456", s);
        }
        {//[u8] => slice
            let s = from_str::<&[u8]>("123456").unwrap();
            assert_eq!(b"123456", s);
        }
        {//Option
            let s = from_str::<Option<i64>>("123456").unwrap();
            assert_eq!(123456, s.unwrap());

            let s = from_str::<Option<i64>>("").unwrap();
            assert_eq!(None, s);
        }

        {//[]
            let s = from_str::<[i64;4]>("[1,2,3,4]").unwrap();
            assert_eq!(&[1, 2, 3, 4][..], s);

            let s = from_str::<Vec<i64>>("[1,2,3,4]").unwrap();
            assert_eq!(&[1, 2, 3, 4][..], s);
        }
        {//tuple
            let (x, y, z, k) = from_str::<(i64, i64, i64, i64)>("[1,2,3,4]").unwrap();
            assert_eq!(x, 1);
            assert_eq!(y, 2);
            assert_eq!(z, 3);
            assert_eq!(k, 4);
        }
        use std::collections::HashMap;
        { //{}
            let s = from_str::<HashMap<String, i64>>("{hello=1,hello2=2}").unwrap();
            assert_eq!(s.len(), 2);

            let s = from_str::<HashMap<String, String>>("{hello=1,hello2=2}").unwrap();
            assert_eq!(s.len(), 2);
        }
        

        { // struct {}
            use serde::Deserialize;
            #[derive(Deserialize)]
            struct Test {
                i: i64,
                s: String,

            }
            let t = from_str::<Test>("i=12,s=string1").unwrap();
            assert_eq!(t.i, 12);
            assert_eq!(t.s, "string1");
        }
        { //TODO: embeded struct A {  struct B {} };
        }
        {//TODO: newtype_struct
        }
    }
    use serde::Deserialize;
    #[test]
    fn de_gtp() {
        #[derive(Deserialize, PartialEq, Debug)]
        enum BuyOrSell {
            Buy,
            Sell,
        }
        #[derive(Deserialize)]
        struct Order {
            id: String,
            price: f64,
            amount: u32,
            buy_or_sell: BuyOrSell, 
        }
        let src = "id=0003344393,price=456.23,amount=1,buy_or_sell=Buy";
        let o = from_str::<Order>(src).unwrap();
        assert_eq!(o.id, "0003344393");
        assert_eq!(o.price, 456.23);
        assert_eq!(o.amount, 1);
        assert_eq!(o.buy_or_sell, BuyOrSell::Buy);
    }

    #[test]
    fn borrowed_bytes() {
        #[derive(Deserialize)]
        struct Order<'a> {
            id: &'a [u8],
            price: f64,
        }
        let src = b"id=000012345,price=456.23";
        let o = from_slice::<Order>(src).unwrap();
        assert_eq!(o.id, b"000012345");
        assert_eq!(o.price, 456.23);
    }
    #[test]
    fn borrowed_str() {
        #[derive(Deserialize)]
        struct Order<'a> {
            id: &'a str,
            price: f64,
        }
        let src = b"id=000012345,price=456.23";
        let o = from_slice::<Order>(src).unwrap();
        assert_eq!(o.id, "000012345");
        assert_eq!(o.price, 456.23);
    }

    #[test]
    fn encoding() {
        #[derive(Deserialize)]
        struct Order<'a> {
            id: &'a [u8],
        }
        // utf8 of I(chinese) => \xE6\x88\x91, so use unknow utf8 code
        let src = b"id=000012345\xE6\x88\x00\x0A\x0D";
        let o = from_slice::<Order>(src).unwrap();
        assert_eq!(o.id, b"000012345\xE6\x88\x00\x0A\x0D");
    }
}

